<template>
    <el-dialog :model-value="show" title="新建公告通知" width="auto" style="min-width: 60%;" align-center
               :close-on-click-modal="false" :before-close="shut"
               destroy-on-close append-to-body>
        <el-form ref="InformRef" :model="informForm" :rules="rules"
                 label-width="170px" status-icon label-position="left"
        >
            <el-form-item label="标题" prop="title">
                <el-input style="width: 100%" v-model="informForm.title" clearable/>
            </el-form-item>
            <el-form-item label="公告通知文件" prop="file" ref="UploadFormRef">
                <el-upload
                    ref="UploadRef"
                    :accept="types" drag
                    :auto-upload="false"
                    :file-list="informFileList"
                    :limit="1"
                    :on-exceed="handleExceed"
                    :on-change="handleChange"
                    :on-preview="handlePreview"
                    :on-remove="handleRemove"
                >
                    <el-icon class="el-icon--upload"><UploadFilled/></el-icon>
                    <template #tip>
                        <div class="el-upload__tip">
                            请上传pdf或docx,大小不超过20M。
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="submitForm(InformRef)">完成</el-button>
                <el-button @click="resetForm">重置</el-button>
                <el-button type="danger" @click="$emit('update:show',false)">取消</el-button>
            </span>
        </template>
    </el-dialog>
    <el-dialog v-model="showPreview" title="预览" width="100%">
        <vue-office-docx
            v-if="isWord"
            :src="previewURL"
            @error="errorHandler"
        />
        <vue-office-pdf
            v-if="!isWord"
            :src="previewURL"
            @error="errorHandler"
        />
    </el-dialog>
</template>

<script setup>
import {ref} from 'vue'
import {UploadFilled} from "@element-plus/icons-vue";
import VueOfficePdf from "@vue-office/pdf";
import VueOfficeDocx from "@vue-office/docx";
import '@vue-office/docx/lib/index.css'
//api
import {createInformApi,} from "@/apis/inform";
import {getInformUploadPresigned, uploadByPresignedUrl} from "@/apis/file";

defineProps(["show"])
const emits = defineEmits(["update:show","reload"])

//通知公告form表单元素
const InformRef = ref(null)
let informForm = ref({
    title:"",
    file:""
})
const rules = {
    title: [{required: true, message: '公告通知标题不能为空!', trigger: ['blur','change']}],
    file: [{required: true, message: '公告通知文件不能为空!', trigger: ['blur','change'],}],
}
const resetForm = () => {
    InformRef.value.resetFields()
    informFileList.value = []
}
const submitForm = formEl => {
    if (!formEl) return
    formEl.validate( async valid => {
        if (valid) {
            informForm.date = new Date();
            informFileList.value[0].status = "uploading"
            const url =  await getInformUploadPresigned(informForm.value.file.name);
            const timer = setInterval(()=>{
                informFileList.value[0].percentage++
                if(informFileList.value[0].percentage === 99) clearInterval(timer)
            },10)
            await uploadByPresignedUrl(url.data, informForm.value.file)
            await createInformApi({
                title:informForm.value.title,
                resourceId:url.data.slice(0,url.data.lastIndexOf("?"))
            })
            clearInterval(timer)
            informFileList.value[0].percentage = 100
            informFileList.value[0].status = "success"
            emits("reload")
            ElMessage.success("公告新建成功")
            resetForm()
            emits("update:show", false)
        }
    })
}
const shut = () => {
    ElMessageBox.confirm(
        '确定关闭吗?',
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        resetForm()
        emits("update:show", false)
    }).catch()
}


const types = "application/pdf,application/docx,application/xml,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
const UploadRef = ref(null)
let informFileList = ref([])
//上传前判断
const handleChange = (file, fileList) => {
    //判断上传格式
    const typeArr = types.split(",")
    let flag = false
    for (const type of typeArr) {
        if (file.raw.type.includes(type)) {
            flag = true
            break
        }
    }
    if (!flag) {
        ElMessage.error("很抱歉您上传的格式不是pdf或docx")
        fileList.pop()
        return
    }
    if (file.raw.size / 1024 / 1024 > 20) {
        ElMessage.error("您上传的文件大小超过了5MB")
        fileList.pop()
        return;
    }

    informFileList.value = [file]
    informForm.value.file = file.raw
    InformRef.value.validateField("file")
}
const handleExceed = files => {
    UploadRef.value.clearFiles()
    UploadRef.value.handleStart(files[0])
}
const handleRemove = () => {
    informForm.value.file = ""
    InformRef.value.validateField("file")
}
//预览框
let showPreview = ref(false)
let previewURL = ref("")
let isWord = ref("")
const handlePreview = file => {
    //提供预览链接
    isWord.value = !file.raw.type.includes("pdf")
    previewURL.value = URL.createObjectURL(file.raw);
    showPreview.value = true
}

const errorHandler = () => {
    ElMessage.error("文件加载失败,请稍后再试")
}
</script>

<style scoped>
.dialog-footer button:first-child {
    margin-right: 10px;
}

.el-form-item {
    margin-bottom: 20px;
}
:deep(.el-upload-list__item-name):hover{
    cursor: pointer;
}
</style>